import * as THREE from 'three';
import { vertexShader, vertexCricleShader, fragmentCricleShader, fragmentShader } from './flyLine.glsl.js';

export function useFlyLine() {
    // 仅创建空 Group，先不挂 scene
    const linesGroup = new THREE.Group();
    linesGroup.visible = false;   // 默认隐藏
    function addTo(scene) {
        scene.add(linesGroup);
    }

    function addFly(scene, opts) {
        const { from, to, color, glow = 3, width = 3, length = 0.3, speed = 1, radius = 1 } = opts;
        /* ✅ 关键：过滤零长度或极短曲线，防止塌陷到原点 */
        if (from.distanceTo(to) < 0.1) return;
        linesGroup.visible = true;// 第一条线出现时整体可见
        // 中间抬高
        const mid = from.clone().add(to).multiplyScalar(0.6);
        mid.y += from.distanceTo(to) * 0.08;
        const curve = new THREE.QuadraticBezierCurve3(from, mid, to); // 原版写法
        const points = curve.getPoints(512); // 512 个点
        const path = new THREE.CatmullRomCurve3(points);
        // 旧版
        const tubeGeo = new THREE.TubeGeometry(path, 512, radius, 18, true);
        const mat = new THREE.ShaderMaterial({
            uniforms: {
                uTime: { value: 0 },  // 关键：第一帧不闪
                uFadeIn: { value: 0.15 },      // 头 15% 时间淡入
                uFadeOut: { value: 0.15 },      // 尾 15% 时间淡出
                uHeadRatio: { value: 0.3 }, // 数值越小尾巴越短
                uWidth: { value: width },
                uMaxWidth: { value: opts.maxWidth || width * 2 }, // 默认不超过 2 倍
                uColor: { value: new THREE.Color(color) },
                // 新增
                uGradient: { value: createdUGradient() },
                uGlowPower: { value: opts.glow || 3.0 }   // 默认 3，可覆盖
            },
            vertexShader,
            fragmentShader,
            transparent: true,
            depthWrite: false,
            blending: THREE.AdditiveBlending   // 让亮部叠加=发光
        });
        const mesh = new THREE.Mesh(tubeGeo, mat);
        linesGroup.add(mesh);

        // 动画
        const duration = 3 / speed; //  底层动画 2s / speed，结束后触发“结束”回调
        let start = performance.now();
        function animate() {
            const elapsed = (performance.now() - start) / 1000;
            const t = elapsed / duration;     // 0 → 1，不再 %1
            if (t >= 1) {
                scene.remove(mesh);
                mesh.geometry.dispose();
                mesh.material.dispose();
                return;
            }
            mat.uniforms.uTime.value = t;
            requestAnimationFrame(animate);
        }
        animate();
    }

    function clear() {
        while (linesGroup.children.length) {
            const child = linesGroup.children.pop();
            child.geometry?.dispose();
            child.material?.dispose();
        }
    }
    // 生成纹理
    function createdUGradient() {
        // 生成 1D 彩虹渐变纹理
        const SIZE = 64;
        const data = new Uint8Array(SIZE * 3);
        for (let i = 0; i < SIZE; i++) {
            const t = i / (SIZE - 1);
            data[i * 3 + 0] = Math.sin(t * Math.PI * 2) * 127 + 128; // R
            data[i * 3 + 1] = Math.sin(t * Math.PI * 2 + 2) * 127 + 128; // G
            data[i * 3 + 2] = Math.sin(t * Math.PI * 2 + 4) * 127 + 128; // B
        }
        const gradientTexture = new THREE.DataTexture(data, SIZE, 1, THREE.RGBFormat);
        gradientTexture.needsUpdate = true;
        return gradientTexture;
    }
    return { addTo, addFly, clear };
}